package cn.bs.securitystudy.service.impl;

import cn.bs.securitystudy.pojo.User;
import cn.bs.securitystudy.service.LoginService;
import cn.bs.securitystudy.util.JwtUtil;
import cn.bs.securitystudy.util.RedisUtil;
import cn.bs.securitystudy.vo.ResponseResult;
import cn.bs.securitystudy.vo.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public ResponseResult login(User user) {

        //通过下面这个实现类,手动把username和userpassword封装成Authentication对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //通过AuthenticationManager的authenticate方法进行认证
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //如果认证没有通过,抛异常
        if (Objects.isNull(authenticate)){
           throw new  RuntimeException("没得这个人");
        }
        //如果通过,就用userid生成一个jwt,jwt存入ResponseResult进行返回
        //通过getPrincipal方法可以拿到之前UserDetails封装的内容,这里知道是用户的登录信息,所以直接强转
        UserLogin userLogin = (UserLogin) authenticate.getPrincipal();
        String userid = userLogin.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        HashMap hashMap = new HashMap<>();
        hashMap.put("token",jwt);
        //把完整的用户信息存入redis,userid作为key
        redisUtil.set("login:"+userid,userLogin);
        return new ResponseResult(200,"登录成功",hashMap);
    }

    //退出登录
    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的userid
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserLogin userLogin = (UserLogin) authentication.getPrincipal();
        Long id = userLogin.getUser().getId();
        //从redis中删除信息
        redisUtil.del("login:"+id);
        return new ResponseResult(200,"注销成功");
    }
}
